<!--  -->
<template>
  <div class="container">
    <div style="
        width: 40%;
        min-height: 70%;
        background: rgb(58, 78, 115);
        padding: 30px;
        border-radius: 8%;
        box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
        display: flex;
        flex-direction: column;
        justify-content: space-between;
      ">
      <el-steps :active="active" finish-status="success">
        <el-step title="选择服务器IP"></el-step>
        <el-step title="系统信息"></el-step>
        <el-step title="注册用户"></el-step>
      </el-steps>

      <el-form :model="ruleForm" ref="ruleForm" label-width="130px" :rules="rules" class="demo-ruleForm">
        <el-form-item label="选择服务器IP" prop="socketIp" v-show="active == 0">
          <el-select v-model="ruleForm.socketIp" placeholder="请选择服务器IP" clearable>
            <el-option v-for="item in ipList" :key="item" :label="item" :value="item" @click.native="changeIp(item)">
            </el-option>
          </el-select>
        </el-form-item>
        <div v-show="active == 1">
          <el-form-item label="LOGO" prop="name">
            <el-upload class="avatar-uploader" :data="{ path: 'logo' }" :action="uploadURL + 'sys/image/uploadImage'"
              :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <img v-if="ruleForm.logoUrl" :src="uploadURL + PathPrefix + ruleForm.logoUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="系统名称" prop="sysName" class="labelWidth">
            <el-input v-model="ruleForm.sysName" placeholder="请输入系统名称·"></el-input>
          </el-form-item>
          <el-form-item label="单位名称" prop="unitName" class="labelWidth">
            <el-input v-model="ruleForm.unitName" placeholder="请输入单位名称"></el-input>
          </el-form-item>
          <el-form-item label="版权信息" prop="copyright" class="labelWidth">
            <el-input v-model="ruleForm.copyright" placeholder="请输入版权信息"></el-input>
          </el-form-item>
          <el-row>
            <el-col :span="8">
              <el-form-item label="容量统计">
                <el-switch v-model="ruleForm.capacityStatisticsFlag" active-color="#13ce66" :active-value="1"
                  :inactive-value="0">
                </el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="8" v-if="ruleForm.capacityStatisticsFlag == 1">
              <el-form-item label="每厘米档案页数" prop="cmPageNo">
                <el-input v-model.number="ruleForm.cmPageNo" placeholder="请输入每厘米档案页数"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div v-show="active == 2">
          <el-form-item label="用户名" prop="username" class="labelWidth">
            <el-input v-model="ruleForm.username" placeholder="请输入用户名" prefix-icon="el-icon-user" clearable disabled />
          </el-form-item>
          <el-form-item label="密码" prop="password" class="labelWidth">
            <el-input v-model="ruleForm.password" placeholder="请输入密码" clearable disabled prefix-icon="el-icon-lock" />
          </el-form-item>
        </div>
      </el-form>
      <div style="display: flex; justify-content: flex-end">
        <el-button type="primary" @click="back()" v-show="active !== 0">上一步</el-button>
        <el-button type="primary" @click="next()">{{ active == 2 ? '激活' : '下一步' }}</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import rule from '@/utils/rule'
import { getServerIP, changServerIP, checkingCode } from '@/api/init'
import { ElMessage } from 'element-plus';

export default {
  name: 'stepIndex',
  components: {},
  data() {
    return {
      active: 0,
      PathPrefix: 'logo/',
      rules: {
        socketIp: [{ required: true, message: '请选择服务器IP', trigger: 'change' }],
        cmPageNo: [{ validator: rule.zzs, trigger: 'blur', required: true }],
        sysName: [
          { required: true, message: '请输入系统名称', trigger: 'blur' },
          { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' },
        ],
      },
      ruleForm: {
        username: 'admin',
        password: '88567889',
      },
      ipList: [],
      serial: {},
      validDays: 0,
    }
  },
  computed: {},
  watch: {},
  created() { },
  mounted() {
    this.getServerIP()
  },
  methods: {
    /**
     *  注册验证第一步  获取服务器的所有ip
     * 第二步 更新ip地址
     * 第三步 验证注册码
     */
    async getServerIP() {
      const res = await getServerIP()
      try {
        if (res.data.code == 0) {
          this.ipList = res.data.ipList
          // 这个表单不可直接赋值，负责会重新定义ruleForm，引起表单校验  需要用响应式处理一下
          this.$set(this.ruleForm, 'id', res.data.setting.id)
          this.$set(this.ruleForm, 'sysName', res.data.setting.sysName)
          this.$set(this.ruleForm, 'unitName', res.data.setting.unitName)
          this.$set(this.ruleForm, 'copyright', res.data.setting.copyright)
          this.$set(this.ruleForm, 'logoUrl', res.data.setting.logoUrl)
          this.$set(
            this.ruleForm,
            'capacityStatisticsFlag',
            res.data.setting.capacityStatisticsFlag
          )
          this.$set(this.ruleForm, 'cmPageNo', res.data.setting.cmPageNo)
        }
      } catch (error) {
        ElMessage.error(error)
      }
    },
    async submitForm() {
      const result = await changServerIP(this.ruleForm)
      try {
        if (result.data.code == 200) {
          ElMessage.success('设置保存成功')
          this.serial = result.data.data
        } else {
          ElMessage.error('设置保存失败，请检查输入数据')
        }
      } catch (error) {
        ElMessage.error(result.data.message)
      }
    },

    // 验证激活码
    async checkingCode(registryCode) {
      const serial = {
        registerId: this.serial.registerId,
        registryCode: registryCode,
        serialNumber: this.serial.serialNumber,
      }
      const result = await checkingCode(serial)

      if (result.data.code === 200) {
        return result.data.data.validDays
      } else {
        return false
      }
    },
    // 更改ip
    changeIp(item) {

    },
    beforeAvatarUpload(file) {
      const isPNG = file.type === 'image/png'
      const isLt1M = file.size / 1024 / 1024 < 1
      if (!isPNG) {
        ElMessage.error('上传LOGO图片只能是 PNG 格式!')
      }
      if (!isLt1M) {
        ElMessage.error('上传LOGO图片大小不能超过 1MB!')
      }
      return isPNG && isLt1M
    },
    handleAvatarSuccess(res, file) {
      this.$set(this.ruleForm, 'logoUrl', res.data)
      // this.ruleForm.logoUrl = res.data
    },
    // 上一步
    back() {
      if (this.active == 2) {
        this.active = 1
      } else if (this.active == 1) {
        this.active = 0
      }
    },
    async validateFieldsAndSubmit() {
      const fieldsToValidate = ['sysName', 'cmPageNo'];
      let isValid = true;
      for (const field of fieldsToValidate) {
        await this.$refs.ruleForm.validateField(field, (valid) => {
          if (valid) {
            isValid = false;
          }
        });
        if (!isValid) {
          break; // 如果有任何一个字段校验失败，停止后续校验
        }
      }
      if (isValid) {
        this.active = 2;
        this.submitForm();
      }
    },
    // 下一步
    next() {
      if (this.active == 0) {
        // 对表单进行单独控制
        this.$refs.ruleForm.validateField('socketIp', (valid) => {
          if (!valid) {
            this.active = 1
          }
        })
      } else if (this.active == 1) {

        this.validateFieldsAndSubmit()

      } else if (this.active == 2) {
        this.$prompt(`${this.serial.serialNumber}    请联系商家获取激活码`, '提示', {
          confirmButtonText: '确定',
          closeOnClickModal: false,
        }).then(async ({ value }) => {
          const validDays = await this.checkingCode(value)
          if (validDays) {
            ElMessage({
              type: 'success',
              message: '系统已激活',
              // message: `系统已激活，有效期剩余${validDays}天`,
            })
            this.$emit('changeGuide')
            this.$emit('getSettingList')
          } else {
            ElMessage.error('激活码错误，请重新输入')
          }
        })
      }
    },
  },
}
</script>
<style lang="less" scoped>
.container {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.el-form-item__label {
  color: #fff;
}

.avatar-uploader {
  .el-upload {
    border: 1px solid #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: contain;
}
</style>
